import { type Option } from '../../types';
import BpmnControlService from '../bpmn/service';
import RadioControl from '../radio';

class RadioElementService extends BpmnControlService<string> {
  element: string;
  field: string;
  defaultValue?: string;
  component = RadioControl;

  options: Option[] = [];

  value: string = '';
  types: string[] = [];

  constructor({ label, field, element, defaultValue, options, types }: {
    label: string, field: string, element: string, defaultValue?: string, options: Option[],
    types: string[]
  }) {
    super({ label, field });
    this.element = element;
    this.field = field;
    this.defaultValue = defaultValue;
    this.options = options;
    this.types = types;
  }

  onChange(value: string) {
    this.value = value;
    this.updateProperties(value);
  }

  updateProperties(value: string) {
    const element = this.panel.getElement();
    const moddle = this.root.getModdle();

    const oldExtensionElements = element.businessObject.extensionElements;
    const oldConfig = oldExtensionElements?.values?.filter((it: any) => it.$type !== this.element) || [];

    const newValue = Array.isArray(value) ? value.join(',') : value;
    // const newConfig = newValue ? [moddle.create(this.element, { value: newValue })] : [];
    const newConfig = [moddle.create(this.element, { value: newValue })];

    const extensionElements = moddle.create(
      'bpmn:ExtensionElements',
      {
        values: [
          ...oldConfig,
          ...newConfig
        ],
      },
    );

    this.root.getModeling().updateProperties(
      element,
      {
        extensionElements
      },
    );
  }

  init() {
    const element = this.panel.getElement();
    const extensionElements = element.businessObject.extensionElements;
    const dom = extensionElements?.values?.find((e: any) => e.$type === this.element);
    // console.log('dom', dom, this.defaultValue, element);
    if (dom) {
      this.value = dom?.[this.field] || '';
    } else {
      // // 触发一次onChange，将默认值写入
      if ((this.defaultValue !== undefined) && this.types.includes(element.type)) {
        this.onChange(this.defaultValue);
      } else {
        this.value = '';
      }
    }
  }

}

export default RadioElementService;
